package com.tgy.algorithm.base._排序;

import java.util.Arrays;

public class _归并排序_01 {

    public static void mergeSort(int[] nums) {

        doMergeSort(nums,0,nums.length-1);
    }

    public static void doMergeSort(int[] nums,int left,int right) {
        if (left >=  right) {
            return;
        }
        int mid = left + ((right - left) >> 1);
        doMergeSort(nums, left, mid);
        doMergeSort(nums, mid + 1, right);
        merge(nums, left, mid, right);
    }


    public static void merge(int[] nums,int left,int mid,int right) {
        int[] tmp = new int[right - left + 1];
        int leftIndex = left;
        int rightIndex = mid + 1;
        int index = 0;
        while (leftIndex <= mid && rightIndex <= right) {
            if (nums[leftIndex] < nums[rightIndex]) {
                tmp[index++] = nums[leftIndex++];
            }else {
                tmp[index++] = nums[rightIndex++];
            }
        }

        while (leftIndex <= mid) {
            tmp[index++] = nums[leftIndex++];
        }
        while (rightIndex <= right) {
            tmp[index++] = nums[rightIndex++];
        }

        for (int i = 0; i < tmp.length; i++) {
            nums[left+i] = tmp[i];
        }
    }

    public static void main(String[] args) {

        int[] nums = new int[]{3, 2, 1, 5, 6, 4};
        mergeSort(nums);
        System.out.println(Arrays.toString(nums));
    }
}
